package cn.zhoujing.demo.oauth.config;

import cn.hutool.core.collection.ListUtil;
import cn.zhoujing.demo.oauth.enity.MyUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author zhoujing
 * @createTime 2023/11/19 - 14:20
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * {@link AuthorizationServerConfig} 认证服务中需要使用，提前放入IOC容器中
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 安全拦截机制
     *
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // CSRF禁用，因为不使用session
                .csrf().disable()
                .authorizeRequests()
                // 登录和静态资源不需要认证
                .antMatchers("/login/**", "/css/**").permitAll()
                // 除上面的所有请求全部需要认证通过才能访问
                .anyRequest().authenticated()
                // 返回HttpSecurity以进行进一步的自定义,证明是一次新的配置的开始
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .permitAll();
    }


    @Bean
    @Override
    public UserDetailsService userDetailsService() {

        return (username) -> {
            if (username.equals("user")) {
                MyUser myUser = new MyUser();
                myUser.setUserName("user");
                myUser.setPassword(passwordEncoder().encode("user"));
                myUser.setAuthorities(ListUtil.of(() -> "user"));
                myUser.setEnabled(true);
                myUser.setAccountNonLocked(true);
                myUser.setAccountNonExpired(true);
                myUser.setCredentialsNonExpired(true);
                return myUser;
            } else if (username.equals("admin")) {
                MyUser myUser = new MyUser();
                myUser.setUserName("admin");
                myUser.setPassword(passwordEncoder().encode("admin"));
                myUser.setAuthorities(ListUtil.of(() -> "admin"));
                myUser.setEnabled(true);
                myUser.setAccountNonLocked(true);
                myUser.setAccountNonExpired(true);
                myUser.setCredentialsNonExpired(true);
                return myUser;
            }
            return null;
        };
    }


}
